package program;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.logging.Logger;
/**
 * Created by Administrator on 2016/11/23.
 */

public class MailInit {
    /*public static InternetAddress getAddress(String address)throws Exception{
        InternetAddress add=new InternetAddress(address);
        return  add;
    }*/
    public static Session init(String host, final String username, final String password) {
        //初始化邮件相关配置信息
        Properties properties = new Properties();
        properties.setProperty("mail.host", host);
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.store.protocol","pop3");
        //创建收发邮件Session
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username,password);
            }
        });
        return session;
    }


    /**
     * 邮件发送（单人）
     */
    public static void sendSingle(String subject, String contect, String username, String password, String address,String host) {

        Session session = MailInit.init(host, username, password);
        //创建mime邮件

        Message message = new MimeMessage(session);
        try {
            //设置发件人
            message.setFrom(new InternetAddress(username));
            //设置主题
            message.setSubject(subject);
            //设置内容
           message.setText(contect);
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(address));
            //发送邮件
            Transport.send(message);
        } catch (MessagingException e) {
            String msg = "邮件发送失败！！";
            throw new RuntimeException(msg);
        }
    }
    public static String[] receiveEmail(String host, String username,String password)throws Exception{
        // 利用Session对象获得Store对象，并连接pop3服务器
        Session session=MailInit.init(host,username,password);
        Store store = session.getStore();
        store.connect();
        //store.connect(pop3Server, user, pwd);

        // 获得邮箱内的邮件夹Folder对象，以"只读"打开
        Folder folder = store.getFolder("inbox");
        folder.open(Folder.READ_ONLY);

        // 获得邮件夹Folder内的所有邮件Message对象
        String[] out=new String[2];
        Message[] messages = folder.getMessages();

        int mailCounts = messages.length;
        //for(int j = mailCounts; j>0; j--) {
            //int i=mailCounts-j;
            String subject = messages[mailCounts-1].getSubject();
            String from = (messages[mailCounts-1].getFrom()[0]).toString();

            System.out.println("最新封邮件的主题：" + subject);
            System.out.println("最新邮件的发件人地址：" + from);

            System.out.println("是否回复该邮件(yes/no)?：");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String input = br.readLine();
            if("yes".equalsIgnoreCase(input)) {
                // 直接输出到控制台中
                messages[mailCounts-1].writeTo(System.out);
                out[0] = messages[mailCounts-1].getContent().toString();
                out[1] = from;
                //}
            }

        folder.close(false);
        store.close();
        return out;
    }


    /*public void sendGroup(String subject,String contect,String username,String password,InternetAddress[] addressGroup)throws  Exception{
        String host = MailInit.getHostByUserName(username);
        Session session =MailInit.init(host, username, password);

        //创建mime邮件
        MimeMessage message = new MimeMessage(session);
        try {
            //设置发件人
            message.setFrom(new InternetAddress(username));
            //设置收件人
            message.addRecipients(RecipientType.TO, addressGroup);
            //设置主题
            message.setSubject("邮件主题");
            //设置内容
            message.setContent(contect,"text/html;charset=utf-8");
            //发送邮件
            Transport.send(message);
        } catch (MessagingException e) {
            String msg = "邮件发送失败！！";
            logger.error(msg);
            throw new RuntimeException(msg);
        }*/
        public static String judgeMeaning(String receive){
            String out;
            if(receive==null){
                out="sorry,I didn't receive your email";
            }
            else {
                boolean judge = receive.contains("?");
                if (judge = true) {
                    out = "yes,I do";
                } else {
                    out = "OK,I known";
                }
            }
            return  out;
        }
        public static void reply(String username,String password)throws Exception{
            String[] out=receiveEmail("pop3.163.com",username,password);
            String contect=judgeMeaning(out[0]);
            sendSingle("reply",contect,username,password,out[1],"smtp.163.com");
        }
        public static void main(String[] args)throws Exception{
            String subject="我的第一封邮件";
            String contect="yichangpengyan@163.com";
            String username="yichangpengyan@163.com";
            String password="weirui199748";
            String[] addresses= MySQL.getAddress();
           for(int i=0;i<addresses.length;i++){
                sendSingle(subject,contect,username,password,addresses[i],"smtp.163.com");
            }
           reply(username,password);
        }
    }
